package info.douyi.dps.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import info.douyi.dps.mapper.InfluenceMapper;
import info.douyi.dps.mapper.PestMapper;
import info.douyi.dps.model.DTO.req.PestUpdateRequestDTO;
import info.douyi.dps.model.DTO.resp.PestFrontResponseDTO;
import info.douyi.dps.model.Pest;
import info.douyi.dps.model.PestExample;
import info.douyi.dps.model.PestWithBLOBs;
import info.douyi.dps.service.PestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class PestServiceImpl implements PestService {

    private static final Logger logger = LoggerFactory.getLogger(PestServiceImpl.class);

    @Autowired
    private PestMapper pestMapper;
    @Autowired
    private InfluenceMapper influenceMapper;

    @Override
    public List<Pest> getAllPest() {
        try {
            if (pestMapper == null) {
                logger.error("PestMapper is null, unable to perform query.");
                return Collections.emptyList();
            }
            List<Pest> pests = pestMapper.selectByExample(null);
            return pests != null ? pests : Collections.emptyList();
        } catch (Exception e) {
            logger.error("An error occurred while querying pests.", e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<PestWithBLOBs> getAllPestWithBLOBs() {
        try{
            List<PestWithBLOBs> pestWithBLOBs = pestMapper.selectByExampleWithBLOBs(null);
            return pestWithBLOBs !=null ? pestWithBLOBs : Collections.emptyList();
        }catch (Exception e){
            logger.error("An error occurred while querying pests.", e);
            return Collections.emptyList();
        }
    }

    @Override
    public PageInfo<Pest> getPestByPage(int pageNum, int pageSize) {
        try{
            PageHelper.startPage(pageNum, pageSize);
            List<Pest> pests = pestMapper.selectByExample(null);
            return new PageInfo<>(pests);
        }catch(Exception e){
            return new PageInfo<>(Collections.emptyList());
        }
    }

    @Override
    public PageInfo<PestFrontResponseDTO> getPestByPageByBid(int bid, int pageNum, int pageSize) {
        // 获取 pid 列表
        List<Integer> pids = influenceMapper.selectPidsByBid(bid);

        PestExample example = new PestExample();
        example.createCriteria().andPidIn(pids);

        // 开始分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Pest> pests = pestMapper.selectByExample(example); // 触发 count 查询和分页查询

        // 转换 DTO
        List<PestFrontResponseDTO> pestsDTO = new ArrayList<>();
        for (Pest p : pests) {
            PestFrontResponseDTO pestDTO = new PestFrontResponseDTO();

            try {
                BufferedImage image = ImageIO.read(new URL(p.getOneimg()));
                pestDTO.setWidth(image.getWidth());
                pestDTO.setHeight(image.getHeight());
            } catch (Exception e) {
                // 获取失败时设置默认值
                pestDTO.setWidth(700);
                pestDTO.setHeight(600);
            }
            if (p.getOneimg() == null) {
                p.setOneimg("https://img.douyi.info/front-end/%E6%9A%82%E6%97%A0%E5%9B%BE%E7%89%87.png");
            }
            BeanUtils.copyProperties(p, pestDTO); // 注意这里应该是从 p 到 pestDTO
            pestsDTO.add(pestDTO);
        }

        // 构建原始的 PageInfo 对象
        PageInfo<Pest> originalPageInfo = new PageInfo<>(pests);

        // 使用原始的 PageInfo 创建一个新的 PageInfo<PestFrontResponseDTO>
        PageInfo<PestFrontResponseDTO> resultPageInfo = new PageInfo<>(pestsDTO);
        // 将分页信息复制到新的 PageInfo 对象中
        resultPageInfo.setTotal(originalPageInfo.getTotal());
        resultPageInfo.setPageNum(originalPageInfo.getPageNum());
        resultPageInfo.setPageSize(originalPageInfo.getPageSize());
        resultPageInfo.setPages(originalPageInfo.getPages());
        resultPageInfo.setPrePage(originalPageInfo.getPrePage());
        resultPageInfo.setNextPage(originalPageInfo.getNextPage());
        resultPageInfo.setIsFirstPage(originalPageInfo.isIsFirstPage());
        resultPageInfo.setIsLastPage(originalPageInfo.isIsLastPage());
        resultPageInfo.setHasPreviousPage(originalPageInfo.isHasPreviousPage());
        resultPageInfo.setHasNextPage(originalPageInfo.isHasNextPage());

        return resultPageInfo;
    }

    @Override
    public PageInfo<Pest> getPestByPageByBidAndPType(int bid, int pType, int pageNum, int pageSize) {
        List<Integer> pids = influenceMapper.selectPidsByBid(bid);
        PestExample example = new PestExample();
        example.createCriteria().andPidIn(pids).andPtypeEqualTo(pType);
        PageHelper.startPage(pageNum, pageSize);
        List<Pest> pests = pestMapper.selectByExample(example);
        return PageInfo.of(pests);
    }

    @Override
    public PestWithBLOBs getPestWithBLOBs(int id) {
        PestWithBLOBs pestWithBLOBs = pestMapper.selectByPrimaryKey(id);

        if (pestWithBLOBs != null) {
            String pathogen = pestWithBLOBs.getPathogen();
            if (pathogen != null && pathogen.length() > 3) {
                // 去掉前3个字符
                pestWithBLOBs.setPathogen(pathogen.substring(3));
            } else {
                // 如果长度不够，可以设为空或保持原样
                pestWithBLOBs.setPathogen(""); // 或者 null
            }

            return pestWithBLOBs;
        } else {
            // 可以抛异常、返回空对象或根据业务需求处理
            throw new RuntimeException("未找到对应的病害信息");
        }
    }

    @Override
    public Pest insertPest(PestWithBLOBs pest) {
        // 插入前可以添加一些逻辑，比如设置创建时间等
        if(pest.getPathogen() != null ){
            // TODO 插入对应的病原体
        }else if (pest.getOneimg() != null ){
            // TODO 插入对应的图片
        }
        else{

        }
        int insert = pestMapper.insert(pest);
        logger.info("尝试插入一个病虫害"+pest.toString());
        return pest;
    }

    @Override
    public Pest getPestByCNName(String cnName) {
        PestExample example = new PestExample();
        example.createCriteria().andNamezhcnEqualTo(cnName);
        List<Pest> pests = pestMapper.selectByExample(example);
        if (!pests.isEmpty()) {
            return pests.getFirst(); // 返回第一个匹配的病虫害
        }else {
            logger.warn("未找到名称为 {} 的病虫害", cnName);
        }
        return null;
    }

    @Override
    public int deletePestById(int id) {
        int deleteCount = pestMapper.deleteByPrimaryKey(id);
        if (deleteCount == 0) {
            logger.warn("未找到ID为 {} 的病虫害，删除操作未执行", id);
        } else {
            logger.info("成功删除ID为 {} 的病虫害", id);
        }
        return deleteCount;
    }


    @Override
    public int updatePest(Pest pest) {
        // 1. 创建 Example 条件
        PestExample example = new PestExample();
        example.createCriteria().andPidEqualTo(pest.getPid()); // WHERE Pid = ?

        // 2. 调用 updateByExample，传两个参数！
        int updateCount = pestMapper.updateByExample(pest, example);

        if (updateCount == 0) {
            logger.warn("未找到ID为 {} 的病虫害，更新操作未执行", pest.getPid());
        } else {
            logger.info("成功更新ID为 {} 的病虫害", pest.getPid());
        }
        return updateCount;
    }

}
